#include "mqcustomplot.h"

MQCustomPlot::MQCustomPlot(QWidget *parent):QCustomPlot(parent)
{
    this->setAntialiasedElement(QCP::AntialiasedElement::aeAll);
    this->addGraph();
    this->addGraph();
    static QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime());
    timeTicker->setTimeFormat("%h:%m");             //时间格式：  分
    this->xAxis->setTicker(timeTicker);  // 横坐标显示时间
    this->xAxis->setLabel("时间(时：分)");
    this->xAxis->setRange(0,24*60*60);

    connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
    connect(this->yAxis, SIGNAL(rangeChanged(QCPRange)), this->yAxis2, SLOT(setRange(QCPRange)));
//    connect(this,&MQCustomPlot::mouseMove, this,&MQCustomPlot::mouseMoveEvent);
    this->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
}

void MQCustomPlot::mouseMoveEvent(QMouseEvent *event)
{
    QCustomPlot::mouseMoveEvent(event);

    //获取点击的点坐标
    QPointF ChickedPoint = event->pos();
    //排除区间外鼠标点
    if(!this->viewport().contains(event->pos())){return;}
    //将像素坐标转换为轴值
    double currentx =this->xAxis->pixelToCoord(ChickedPoint.x());
    double currenty = this->yAxis->pixelToCoord(ChickedPoint.y());
    //使用QToolTip输出值，
    QToolTip::showText(mapToGlobal(event->pos()),QString("(%1, %2)").arg(currentx).arg(currenty),this);
}

void MQCustomPlot::setDB(QString dbName, QString tableName, QString yLabel)
{
    this->dbName = dbName;
    this->tableName = tableName;
    this->yAxis->setLabel(yLabel);
}

void MQCustomPlot::insertValue(double key, double value)
{
    this->graph(0)->addData(key, value);
    QSqlDatabase database;
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName(dbName);
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
        qDebug() << "Succeed to connect database." ;
    }

    //创建表格
    QSqlQuery sql_query;
    if(!sql_query.exec(QString("create table if not exists %1 (time timestamp primary key default (datetime('now','localtime')), value double)").arg(tableName)))
    {
        qDebug() << "Error: Fail to create table."<< sql_query.lastError();
    }

    //插入数据
    if(!sql_query.exec(QString("INSERT INTO %1 (value) values (%2)").arg(tableName).arg(value)))
    {
        qDebug() << sql_query.lastError();
    }
    else
    {
        qDebug() << "insert successfully done!";
    }
    database.close();
    this->replot();
}
